import React, { useState, useMemo, useCallback, useReducer } from 'react'
import HelloWorld from './components/HelloWorld/HelloWorld'
import ControllerInput from './components/ControllerInput/ControllerInput'
import TodoList from './components/TodoList/TodoList'
import Hi from './components/Hi/Hi'

function App() {
  const [flag, setFlag] = useState(true)
  const [a] = useState(1)
  const [b, setB] = useState(2)
  const [c, setC] = useState(3)
  let [count, dispatch] = useReducer((state, action) => {
    console.log('action=>', action)
    switch (action.type) {
      case 'INC':
        return state + 1
      case 'INC_STEP':
        state += action.step
        return state
      default:
        return state
    }
  }, 100)

  const sum = () => {
    console.log('sum函数')
    return a + b
  }

  const sumCache = useMemo(sum, [a, b])

  const toggleFlag = () => {
    setFlag(!flag)
  }
  return (
    <>
      <div className="app-container">
        <div>count:{count}</div>
        <div>
          <button
            onClick={() => {
              dispatch({ type: 'INC' })
            }}
          >
            IncCount
          </button>
          <button
            onClick={() => {
              dispatch({ type: 'INC_STEP', step: 100 })
            }}
          >
            INC_STEP
          </button>
        </div>
        <Parent />
        <div>
          <div>a:{a}</div>
          <div>
            b:{b}
            <button
              onClick={() => {
                setB((preB) => (preB += 1))
              }}
            >
              b++
            </button>
          </div>
          <div>a+b = {sumCache}</div>
          <div>
            c:{c}
            <button
              onClick={() => {
                setC((preC) => (preC += 1))
              }}
            >
              c++
            </button>
          </div>
        </div>
        <h1>待办事项列表</h1>
        <TodoList />
        <ControllerInput>插槽内容</ControllerInput>
        <button onClick={toggleFlag}>Hi组件显/隐</button>
        {flag && <Hi />}
        <HelloWorld name="黄佳琪" />
      </div>
    </>
  )
}

const Parent = React.memo(() => {
  const [count, setCount] = useState(0)

  // 每次render此函数都会重新初始化,useCallback可以缓存函数引用
  const inc = useCallback((step) => {
    console.log('useCallback')
    setCount((count) => count + step)
  }, [])

  console.log('Parent  render')

  return (
    <div>
      <h1
        onClick={() => {
          setCount((count) => (count += 1))
        }}
      >
        父组件: {count}
      </h1>
      <Child inc={inc} />
    </div>
  )
})

const Child = React.memo((props) => {
  console.log('Child render')
  return (
    <div>
      <h2>子组件</h2>
      <button onClick={() => props.inc(1)}>1</button>
      <button onClick={() => props.inc(2)}>2</button>
    </div>
  )
})

export default App
